package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.annotation.Log;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.IotMsgNotifyData;
import com.zzyl.nursing.mapper.DeviceMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.Map;

/**
 * s设备数据Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-03
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询s设备数据
     *
     * @param id s设备数据主键
     * @return s设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询s设备数据列表
     *
     * @param deviceData s设备数据
     * @return s设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData) {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增s设备数据
     *
     * @param deviceData s设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改s设备数据
     *
     * @param deviceData s设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除s设备数据
     *
     * @param ids 需要删除的s设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除s设备数据信息
     *
     * @param id s设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 批量插入设备数据
     *
     * @param iotMsgNotifyData
     */
    @Override
    public void insertDevData(IotMsgNotifyData iotMsgNotifyData) {

        String iotId = iotMsgNotifyData.getHeader().getDeviceId();

        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (device == null) {
            log.error("设备不存在");
            return;
        }
        iotMsgNotifyData.getBody().getServices().forEach(service -> {
            Map<String, Object> properties = service.getProperties();
            if (properties == null) {
                return;
            }
            String eventTimeStr = service.getEventTime();
            LocalDateTime localDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(localDateTime);

            List<DeviceData> list = new ArrayList<>();
            properties.forEach((key, value) -> {
                DeviceData bean = BeanUtil.toBean(device, DeviceData.class);
                bean.setId(null);
                bean.setAccessLocation(device.getBindingLocation());
                bean.setAlarmTime(eventTime);
                bean.setFunctionId(key);
                bean.setDataValue(value.toString());
                list.add(bean);
            });
            this.saveBatch(list);
            log.warn("设备数据保存成功");


            // 存入到redis  key：hash数据类型（大key，小key,  value）iot:device_last_data   iot_id
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, device.getIotId(), JSONUtil.toJsonStr(list));

        });


    }
}
